package com.easy.auth.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import com.easy.auth.domain.Action;
import com.easy.auth.service.ActionService;
import com.easy.base.service.impl.EManagerImpl;
import com.easy.common.util.BeanUtil;
import com.easy.common.web.PagedList;

@Service
public class ActionServiceImpl extends EManagerImpl<Action> implements
		ActionService {

	@SuppressWarnings("unchecked")
	@Override
	public PagedList<Action> getAllActions() {
		String sql = "SELECT * FROM action order by sort asc  ";
		List<Action> list = super.queryList(
				sql,
				null,
				new BeanPropertyRowMapper<Action>(BeanUtil.getGenericType(this,
						0)));
		// List<Action> list = super.findList(new Action());
		return new PagedList<Action>(list);
	}

	@Override
	public Action findActionById(Action action) {
		return super.findByOid(action);
	}

	@Override
	public int saveAction(Action action) {
		if (action.getOid() != null && !"".equals(action.getOid())) {
			action.setSort(super.findByOid(action).getSort()); // 编辑
		} else {
			action.setSort(getSortNo()); // 添加
		}
		return super.saveOrEdit(action);
	}

	@Override
	public int removeActions(String[] oids) {
		List<Action> actionlist = new ArrayList<Action>();
		for (String oid : oids) {
			Action action = new Action();
			action.setOid(oid);
			actionlist.add(action);
		}
		return super.removeAll(actionlist);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Action> getActionByUserId(String userId, String parent) {

		String sql = "SELECT * FROM action WHERE  oid IN("
				+ "SELECT ad.actionid FROM action_department AS ad, userinfo_department AS ud WHERE "
				+ "ad.departmentid = ud.departmentid AND ud.userid ='"
				+ userId
				+ "' UNION SELECT roa.actionid FROM role_action AS roa, userinfo_role AS uro WHERE roa.roleid = "
				+ "uro.roleid AND uro.userId ='" + userId
				+ "' UNION SELECT actionid FROM userinfo_action WHERE userid='"
				+ userId + "')";

		if (parent == null) {
			sql += " and parent is null";
		} else {
			sql += " and parent ='" + parent + "'";
		}
		sql += " ORDER BY sort asc";

		return super.queryList(sql, null, new BeanPropertyRowMapper<Action>(
				BeanUtil.getGenericType(this, 0)));
	}

	@SuppressWarnings("unchecked")
	@Override
	public PagedList<Action> getActionsByUserId(String userid) {
		String sql = "SELECT oid,oname,url,parent,CASE WHEN (oid  IN (SELECT userinfo_action.actionid FROM userinfo_action WHERE userinfo_action.userid='"
				+ userid
				+ "')) THEN 'true 'ELSE null END AS checked FROM action ORDER BY sort asc";
		List<Action> actionList = super.queryList(
				sql,
				null,
				new BeanPropertyRowMapper<Action>(BeanUtil.getGenericType(this,
						0)));
		return new PagedList<Action>(actionList);
	}

	@Override
	public int updateUserActions(String userid, String[] chekcedIds) {
		String deleteSql = "DELETE FROM userinfo_action WHERE userid = ?";
		super.update(deleteSql, userid);

		StringBuffer buffer = new StringBuffer();
		buffer.append("insert into userinfo_action values");

		for (int i = 0; i < (chekcedIds.length); i++) {
			buffer.append("(\'");
			buffer.append(userid + "\', \'" + chekcedIds[i]);
			buffer.append("\'),");
		}
		String updateSql = buffer.toString().substring(0,
				buffer.toString().length() - 1);

		return super.update(updateSql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PagedList<Action> getActionsByRoleId(String roleid) {
		String sql = "SELECT oid,oname,url,parent,CASE WHEN (oid  IN (SELECT role_action.actionid FROM role_action WHERE role_action.roleid='"
				+ roleid
				+ "')) THEN 'true 'ELSE null END AS checked FROM action ORDER BY sort asc";
		List<Action> actionList = super.queryList(
				sql,
				null,
				new BeanPropertyRowMapper<Action>(BeanUtil.getGenericType(this,
						0)));

		return new PagedList<Action>(actionList);
	}

	@Override
	public int updateRoleActions(String roleid, String[] checkedids) {
		String deleteSql = "DELETE FROM role_action WHERE roleid = ?";
		super.update(deleteSql, roleid);

		StringBuffer buffer = new StringBuffer();
		buffer.append("insert into role_action values");

		for (int i = 0; i < (checkedids.length); i++) {
			buffer.append("(\'");
			buffer.append(roleid + "\', \'" + checkedids[i]);
			buffer.append("\'),");
		}
		String updateSql = buffer.toString().substring(0,
				buffer.toString().length() - 1);

		return super.update(updateSql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PagedList<Action> getActionsByDeptId(String deptId) {
		String sql = "SELECT oid,oname,url,parent,CASE WHEN (oid  IN (SELECT action_department.actionid FROM action_department WHERE action_department.departmentid='"
				+ deptId
				+ "')) THEN 'true 'ELSE null END AS checked FROM action  ORDER BY sort asc";
		List<Action> actionList = super.queryList(
				sql,
				null,
				new BeanPropertyRowMapper<Action>(BeanUtil.getGenericType(this,
						0)));
		return new PagedList<Action>(actionList);
	}

	@Override
	public int updateDeptActions(String deptId, String[] checkedids) {

		String deleteSql = "DELETE FROM action_department WHERE departmentid = ?";
		super.update(deleteSql, deptId);

		StringBuffer buffer = new StringBuffer();
		buffer.append("insert into action_department values");

		for (int i = 0; i < (checkedids.length); i++) {
			buffer.append("(\'");
			buffer.append(checkedids[i] + "\', \'" + deptId);
			buffer.append("\'),");
		}
		String updateSql = buffer.toString().substring(0,
				buffer.toString().length() - 1);

		return super.update(updateSql);
	}

	public String getSortNo() {
		String sql = "SELECT MAX(sort) FROM action";
		int sortNo = super.getJdbcTemplate().queryForObject(sql, Number.class)
				.intValue();
		return String.valueOf(sortNo + 1);
	}

	public int changeSort(String firstId, String secondId) {
		int count = 0;
		Action firstAction = new Action();
		firstAction.setOid(firstId);

		Action secondAction = new Action();
		secondAction.setOid(secondId);
		firstAction = super.findByOid(firstAction);
		secondAction = super.findByOid(secondAction);

		String sort1 = firstAction.getSort();
		String sort2 = secondAction.getSort();

		secondAction.setSort("-1");
		count += super.edit(secondAction);

		firstAction.setSort(sort2);
		count += super.edit(firstAction);

		secondAction.setSort(sort1);
		count += super.edit(secondAction);

		return count;
	}

}